#include "widget.h"
#include "ui_widget.h"

#include <QMessageBox>
#include <QTcpSocket>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 1.修改窗口标题
    this->setWindowTitle("服务器");

    // 2.创建QTcpServer的实例
    tcpServer = new QTcpServer(this);

    // 3.连接信号槽，指定如何处理连接
    connect(tcpServer, &QTcpServer::newConnection, this, &Widget::processConnection);

    // 4.绑定并监听端口号，这一步一定得是初始化的最后一步，把准备工作都做好之后，才能真正开始监听
    if (!tcpServer->listen(QHostAddress::Any, 8080))
    {
        // 绑定失败，弹出对话框提示
        QMessageBox::critical(this, "服务器启动失败", tcpServer->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    // 1.通过TcpServer拿到一个socket对象，通过这个对象来和客户端进行通信
    QTcpSocket* clientSocket = tcpServer->nextPendingConnection();
    // 把客户端上线信息显示到界面上
    QString log = "[" + clientSocket->peerAddress().toString()
            + ":" + QString::number(clientSocket->peerPort()) + "] 客户端上线";
    ui->listWidget->addItem(log);

    // 2.通过信号槽，来处理客户端发来请求的情况
    connect(clientSocket, &QTcpSocket::readyRead, this, [=](){
        // a.读取出请求数据
        QString request = clientSocket->readAll();
        // b.根据请求处理响应
        const QString& response = process(request);
        // c.把响应写回到客户端
        clientSocket->write(response.toUtf8());
        // d.把上述信息记录到日志中
        QString log = "[" + clientSocket->peerAddress().toString()
                + ":" + QString::number(clientSocket->peerPort())
                + "] req: " + request + "resp: " + response;
        ui->listWidget->addItem(log);
    });

    // 3.通过信号槽，来处理客户端断开连接的情况
    connect(clientSocket, &QTcpSocket::disconnected, this, [=](){
        // a.把断开连接的信息通过日志显示出来
        QString log = "[" + clientSocket->peerAddress().toString()
                + ":" + QString::number(clientSocket->peerPort()) + "] 客户端下线";
        ui->listWidget->addItem(log);
        // b.手动释放clientSocket
        // delete clientSocket;
        clientSocket->deleteLater();
    });
}

QString Widget::process(const QString &request)
{
    return request;
}

